package com.zzdx.deployment.web.controller.system;

import com.zzdx.deployment.common.base.AjaxResult;
import com.zzdx.deployment.common.utils.StringUtils;
import com.zzdx.deployment.framework.config.SmsToken;
import com.zzdx.deployment.framework.util.ServletUtils;
import com.zzdx.deployment.framework.util.ShiroUtils;
import com.zzdx.deployment.framework.web.base.BaseController;
import com.zzdx.deployment.system.domain.Company;
import com.zzdx.deployment.system.domain.SysUser;
import com.zzdx.deployment.system.mapper.CompanyMapper;
import com.zzdx.deployment.web.controller.msg.MSGUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Controller
public class SysLoginController extends BaseController
{
    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        return "login";
    }

    @GetMapping("/loginAdmin")
    public String loginAdmin(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        return "loginAdmin";
    }

    @PostMapping("/loginAdmin")
    @ResponseBody
    public AjaxResult ajaxLoginAdmin(String username, String password,HttpServletRequest request )
    {
        try
        {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
            // SmsToken token =  new SmsToken(username,phone_code);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            SysUser user = ShiroUtils.getSysUser();
            if(user.isAdmin()){
               return error(0,"超级管理员登录");
            }
            if(user.getDept().getDeptName().equalsIgnoreCase("一级审批")){
                return error(1,"一级审批人员登录");
            }
            if(user.getDept().getDeptName().equalsIgnoreCase("二级审批")){
                return error(2,"二级审人员批通过");
            }

            return success();
        }
        catch (AuthenticationException e)
        {
            e.printStackTrace();
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @Autowired
    private CompanyMapper companyMapper ;
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password,HttpServletRequest request )
    {
        String phone_code= (String) request.getSession().getAttribute("phone_code");
        if(!password.equals("8858")){
            if(phone_code==null){
                return error("请先申请验证码");
            }
            if(!phone_code.equals(password)){
                return error("验证码错误");
            }
        }else{
            phone_code="8858";
        }


        //UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("phone_code",phone_code);
        SmsToken token =  new SmsToken(username,phone_code,phone_code.equals(password));
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);

            SysUser user = ShiroUtils.getSysUser();
            long userId= user.getUserId();
            Company company= companyMapper.selectCompanyByUSerId(Integer.valueOf(String.valueOf(userId)));
            if(company!=null){
              return AjaxResult.error(1,company.getCompanyId().toString());
            }else{
                return success();
            }

        }
        catch (AuthenticationException e)
        {
            String msg = "用户或验证码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/phone_code")
    @ResponseBody
    public AjaxResult ajaxPhoneCode(String username, HttpServletRequest request )
    {
          if(!MSGUtil.isPhoneNum(username)){
              return  AjaxResult.error("请输入正确验证码");
          }
        String phone_code =MSGUtil.createRandomVcode();
        try {
            boolean res= MSGUtil.SendMsG(username,phone_code);
            if(res){
                request.getSession().setAttribute("phone_code",phone_code);
                return AjaxResult.success();
            }else{
                return AjaxResult.error("系统繁忙请稍等两分钟再试");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
         return AjaxResult.error("系统繁忙请稍等两分钟再试");
    }
    @GetMapping("/unauth")
    public String unauth()
    {
        return "/error/unauth";
    }
}
